package ldh.serialize.type;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import ldh.serialize.BinarySerialized;
import ldh.serialize.Serialized;
import ldh.serialize.StringSerialized;
import ldh.serialize.io.ByteBuf;
import ldh.serialize.util.SerializedUtil;
import ldh.serialize.util.TransferUtil;

public class ArraySerialized<T> implements BinarySerialized<T[]> {

	public Serialized<T> serialized;
	
	public ArraySerialized(Serialized<T> serialized) {
		this.serialized = serialized;
	}
	
	@Override
	public void write(ByteBuf out, T[] ts) throws IOException {
		if (!(serialized instanceof BinarySerialized)) {
			throw new RuntimeException("serialized is not BinarySerialized");
		}
		BinarySerialized<T> binarySerialized = (BinarySerialized<T>) serialized;
		out.writeBytes(TransferUtil.intToBytes(ts.length));
		for (T t : ts) {
			binarySerialized.write(out, t);
		}
	}

	@Override
	public T[] read(ByteBuf in) throws IOException {
		if (!(serialized instanceof BinarySerialized)) {
			throw new RuntimeException("serialized is not BinarySerialized");
		}
		int size = SerializedUtil.readInteger(in);
		List<T> ts = new ArrayList<T>(size);
		BinarySerialized<T> binarySerialized = (BinarySerialized<T>) serialized;
		for (int i=0; i<size; i++) {
			T t = binarySerialized.read(in);
			ts.add(t);
		}
		
		T[] tts = (T[]) ts.toArray();
		return tts;
	}

	@Override
	public Class<T[]> getClassType() {
		return null;
	}

}
